//
//  AddNewCarLogViewController.m
//  Rail
//
//  Created by hychen on 2018/3/4.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "AddNewCarLogViewController.h"
#import "TextFieldTableViewCell.h"
#import "LineDetailDescTableViewCell.h"
#import "SelectPhotoTableViewCell.h"
#import "ButtonTableViewCell.h"

#import "WarnLevelConfig.h"

#import "SelectFactoryViewController.h"

#import "BMUsefulPickerView.h"

@interface AddNewCarLogViewController ()
@property (nonatomic, strong) NSDate *loginTime;
@property (nonatomic, strong) NSMutableArray *selectCarPhotoArray;
@property (nonatomic, strong) NSMutableArray *selectLoginPhotoArray;
//离岗年月日
@property (nonatomic, copy) NSString *inDateString;
//离岗时分
@property (nonatomic, copy) NSString *inTimeString;
@property (nonatomic, assign) CarType carType;
@property (nonatomic, copy) NSString *carNo;
@property (nonatomic, copy) NSString *carOwner;
@property (nonatomic, copy) NSString *mobile;
@property (nonatomic, copy) NSString *driverNo;
@property (nonatomic, copy) NSString *note;

@property (nonatomic, copy) NSString *areaId;
@property (nonatomic, copy) NSString *areaName;

@property (nonatomic, assign) BOOL isUploading;
@end

@implementation AddNewCarLogViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.loginTime = [NSDate date];
    self.isOpenHeader = NO;
    [self.navigationItem addSimpleTitleView:@"新增进岗"];
    
    self.inDateString = [self.loginTime formatYearMonthDay_lib];
    self.inTimeString = [NSString stringWithFormat:@"%02ld:%02ld",self.loginTime.hour,self.loginTime.minute];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTableView)];
    tap.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tap];
    
    [self setupTableViewData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)clickTableView {
    [self.view endEditing:YES];
}

- (void)setupTableViewData {
    
    NSString *carTypeString = [WarnLevelConfig carTypeStringWithType:self.carType];
    
    self.dataArray = @[
                       @{@"type":@"text",@"title":@"登记工区",@"data":self.areaName?:@"",@"placeholder":@"请选择工区"},
                       @{@"type":@"text",@"title":@"进岗日期",@"data":self.inDateString?:@"",@"placeholder":@""},
                       @{@"type":@"text",@"title":@"进岗时间",@"data":self.inTimeString?:@"",@"placeholder":@""},
                       @{@"type":@"text",@"title":@"车型选择",@"data":carTypeString?:@"",@"placeholder":@"请选择车型"},
                       @{@"type":@"textfield",@"title":@"车牌号码",@"data":self.carNo?:@"",@"placeholder":@"请输入车牌号码"},
                       @{@"type":@"textfield",@"title":@"车主姓名",@"data":self.carOwner?:@"",@"placeholder":@"请输入车主姓名"},
                       @{@"type":@"textfield",@"title":@"联系手机",@"data":self.mobile?:@"",@"placeholder":@"请输入手机号码"},
                       @{@"type":@"textfield",@"title":@"驾驶证号",@"data":self.driverNo?:@"",@"placeholder":@"请输入驾驶证号"},
                     @{@"type":@"image",@"title":@"驾驶证照",@"data":@"",@"placeholder":@""},
                       @{@"type":@"image",@"title":@"进岗照片",@"data":@"",@"placeholder":@""},
                       @{@"type":@"textfield",@"title":@"备注信息",@"data":self.note?:@"",@"placeholder":@"请输入备注信息"},
                       @{@"type":@"button",@"title":@"保存",@"data":@"",@"placeholder":@""},
                       ].mutableCopy;
    
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
    NSString *type = [dict objectForKey:@"type"];
    
    BMWeakSelf
    if ([type isEqualToString:@"textfield"]) {
        TextFieldTableViewCell *cell = [TextFieldTableViewCell cellWithInitStyleTableView:tableView class:[TextFieldTableViewCell class]];
        cell.placeholder = [dict objectForKey:@"placeholder"];
        cell.title = [dict objectForKey:@"title"];
        cell.content = [dict objectForKey:@"data"];
        if (indexPath.row == 6) {
            cell.tf.keyboardType = UIKeyboardTypeNumberPad;
        }
        else {
            cell.tf.keyboardType = UIKeyboardTypeDefault;
        }
        cell.BlockEndEditing = ^(NSString *text) {
            if (indexPath.row == 4) {
                weakSelf.carNo = text;
            }
            else if (indexPath.row == 5) {
                weakSelf.carOwner = text;
            }
            else if (indexPath.row == 6) {
                weakSelf.mobile = text;
            }
            else if (indexPath.row == 7) {
                weakSelf.driverNo = text;
            }
            else if (indexPath.row == 10) {
                weakSelf.note = text;
            }
            [weakSelf setupTableViewData];
        };
        return cell;
    }
    else if ([type isEqualToString:@"image"]) {
        SelectPhotoTableViewCell *cell = [SelectPhotoTableViewCell cellWithInitStyleTableView:tableView class:[SelectPhotoTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setTitle:[dict objectForKey:@"title"]];
        if (indexPath.row == 8) {
            cell.maxCount = 1;
            [cell setPhotoArray:self.selectCarPhotoArray];
        }
        else if (indexPath.row == 9) {
            cell.maxCount = 2;
            [cell setPhotoArray:self.selectLoginPhotoArray];
        }
        
        [cell setBlockSelectPhotoArray:^(NSArray *photoArray) {
            if (indexPath.row == 8) {
                weakSelf.selectCarPhotoArray = [NSMutableArray arrayWithArray:photoArray];
            }
            else if (indexPath.row == 9) {
                weakSelf.selectLoginPhotoArray = [NSMutableArray arrayWithArray:photoArray];
            }
        }];
        return cell;
    }
    else if ([type isEqualToString:@"text"]) {
        LineDetailDescTableViewCell *cell = [LineDetailDescTableViewCell cellWithTableView:tableView class:[LineDetailDescTableViewCell class]];
        cell.showArrow = YES;
        cell.titleLabel.text = [dict objectForKey:@"title"];
        NSString *data = [dict objectForKey:@"data"];
        if (!([data isKindOfClass:[NSString class]] && data.length > 0)) {
            data = [dict objectForKey:@"placeholder"];
            cell.isPlaceholder = YES;
        }
        else {
            cell.isPlaceholder = NO;
        }
        cell.contentLabel.text = data;
        return cell;
    }
    else if ([type isEqualToString:@"button"]) {
        ButtonTableViewCell *cell = [ButtonTableViewCell cellWithTableView:tableView class:[ButtonTableViewCell class]];
        NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.buttonTitle = [dict objectForKey:@"title"];
        BMWeakSelf
        [cell setBlockClickEventButton:^{
            [weakSelf.view endEditing:YES];
            [weakSelf requestAddLoginData];
        }];
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 8) {
        return 50.f;
    }
    else if (indexPath.row < 10) {
        return 160.f;
    }
    else if (indexPath.row < 11) {
        return 50.f;
    }
    else if (indexPath.row < 12) {
        return 80.f;
    }
    return 0.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BMWeakSelf
    if (indexPath.row == 0) {
        //选择工区
        SelectFactoryViewController *vc = [SelectFactoryViewController new];
        vc.style = SelectFactoryControllerStyleScanSelectFactory;
        BMWeakSelf
        [vc setBlockCallBack:^(NSString *areaId, NSString *areaName) {
            weakSelf.areaId = areaId;
            weakSelf.areaName = areaName;
            [weakSelf setupTableViewData];
        }];
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row == 1) {
        BMDatePickerViewStyle *style = [BMDatePickerViewStyle new];
        style.date = [NSDate date];
        style.maximumDate = style.date;
        style.datePickerMode = UIDatePickerModeDate;
        [BMUsefulPickerView showDatePickerWithToolBarText:@"进岗日期" withStyle:style toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSDate *selectedDate) {
            weakSelf.inDateString = [selectedDate formatYearMonthDay_lib];
            [weakSelf setupTableViewData];
        } valueChangeBlock:^(NSDate *selectedDate) {
            
        }];
    }
    else if (indexPath.row == 2) {
        BMDatePickerViewStyle *style = [BMDatePickerViewStyle new];
        style.date = [NSDate date];
        style.maximumDate = style.date;
        style.datePickerMode = UIDatePickerModeTime;
        [BMUsefulPickerView showDatePickerWithToolBarText:@"进岗时间" withStyle:style toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSDate *selectedDate) {
            weakSelf.inTimeString = [selectedDate formatMinuteSecond_lib];
            [weakSelf setupTableViewData];
        } valueChangeBlock:^(NSDate *selectedDate) {
            
        }];
    }
    else if (indexPath.row == 3) {
        [BMUsefulPickerView showSingleColPickerWithToolBarText:@"选择车型" data:[WarnLevelConfig carTypeStringArray] defaultIndex:0 toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSInteger selectedIndex, NSString *selectedValue) {
            weakSelf.carType = (CarType)selectedIndex;
            [weakSelf setupTableViewData];
        }];
    }
}

#pragma mark 网络请求
- (void)requestAddLoginData {
    BMWeakSelf
    if (self.isUploading) {
        return;
    }
    
    if (![self.areaId objectIsNotEmpty]) {
        Show_Msg_Error(@"请选择工区")
        return;
    }
    
    if (![self.carOwner objectIsNotEmpty]) {
        Show_Msg_Error(@"请输入车主姓名")
        return;
    }
    
    if (![self.mobile objectIsNotEmpty]) {
        Show_Msg_Error(@"请输入联系手机")
        return;
    }
    
    if (![self.carNo objectIsNotEmpty]) {
        Show_Msg_Error(@"请输入车牌号码")
        return;
    }
    
    if (self.selectCarPhotoArray.count < 1) {
        Show_Msg_Error(@"请上传驾驶证照")
        return;
    }
    
    if (self.selectLoginPhotoArray.count < 1) {
        Show_Msg_Error(@"请上传进岗照片")
        return;
    }
    
    if (![self.driverNo objectIsNotEmpty]) {
        Show_Msg_Error(@"请输入驾驶证号")
        return;
    }
    
    if (![CheckUtility checkForMobilePhoneNo:self.mobile?:@""]) {
        Show_Msg_Error(@"手机号码格式错误")
        return;
    }
    
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf _requestAddLoginData];
    }]) {
        return;
    }
    
    [self _requestAddLoginData];
}

- (void)_requestAddLoginData {
    BMWeakSelf
    
    UIImage *driverImage = nil;
    if (self.selectCarPhotoArray.count > 0) {
        SelectPhotoModel *imageModel = [self.selectCarPhotoArray objectAtIndex:0];
        driverImage = [imageModel uploadImage]?:[imageModel image];
    }
    
    UIImage *image1 = nil;
    if (self.selectLoginPhotoArray.count > 0) {
        SelectPhotoModel *imageModel = [self.selectLoginPhotoArray objectAtIndex:0];
        image1 = [imageModel uploadImage]?:[imageModel image];
    }
    
    UIImage *image2 = nil;
    if (self.selectLoginPhotoArray.count > 1) {
        SelectPhotoModel *imageModel = [self.selectLoginPhotoArray objectAtIndex:1];
        image2 = [imageModel uploadImage]?:[imageModel image];
    }
    
    NSString *inTime = [NSString stringWithFormat:@"%@ %@",self.inDateString,self.inTimeString];
    self.isUploading = YES;
    
    Show_Msg(@"进岗中")
    [HttpRequest requestCarInWithPlateNum:self.carNo?:@"" driveName:self.carOwner?:@"" mobile:self.mobile?:@"" driverCard:self.driverNo?:@"" carType:self.carType areaId:self.areaId?:@"" note:self.note?:@"" driverImage:driverImage inTime:inTime inImage1:image1 inImage2:image2 success:^(id object) {
        weakSelf.isUploading = NO;
        Show_Msg_Success(@"进岗成功")
        if (weakSelf.BlockLoginCarSuccess) {
            weakSelf.BlockLoginCarSuccess();
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
            Dismiss_NoMsg
        });
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg)
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}


@end
